//
//  FinderList.swift
//  WYYao
//
//  Created by wangcl on 2024/9/11.
//

import Foundation
import UIKit

class FinderList:ObservableObject{
    let url:URL
    @Published var items:[FinderItem] = []
    
    var relativePath:String{
        FinderList.relativePath(for: url)
    }
    init(url:URL){
        self.url = url
        refresh()
    }
    func refresh(){
        items = FinderList.item(for:url)
    }
}
extension FinderList {
    static var rootURL:URL {
        guard let documentDir = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) else {
            fatalError()
        }
        return documentDir
    }
    static func relativePath(for url:URL) -> String {
        let path = url.path.replacingOccurrences(of:rootURL.path , with: "")
        return path.isEmpty ? "/" : path
    }
    static func item(for url:URL) -> [FinderItem]{
        guard let urls = try? FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: [.contentModificationDateKey,.isDirectoryKey]) else {
            fatalError()
        }
        return urls.map { FinderItem(url: $0) }.sorted {
            $0.contentModificationDate > $1.contentModificationDate
        }
    }
}
